package dict

var _ Dict[int, int] = &UnsafeDict[int, int]{}

// UnsafeDict 定义非并发安全的字典类型
type UnsafeDict[K comparable, V any] struct {
	items map[K]V
}

// NewUnsafeDict 新建一个非并发安全的字典
func NewUnsafeDict[K comparable, V any]() *UnsafeDict[K, V] {
	return &UnsafeDict[K, V]{items: make(map[K]V)}
}

// Set 设置键值对
func (own *UnsafeDict[K, V]) Set(key K, val V) {
	own.items[key] = val
}

// Update 更新字典
func (own *UnsafeDict[K, V]) Update(items map[K]V) {
	for key, val := range items {
		own.items[key] = val
	}
}

// Delete 删除键值对
func (own *UnsafeDict[K, V]) Delete(keys ...K) {
	for _, key := range keys {
		delete(own.items, key)
	}
}

// HasAll 判断所有指定键值对是否存在
func (own *UnsafeDict[K, V]) HasAll(keys ...K) bool {
	for _, key := range keys {
		if _, ok := own.items[key]; !ok {
			return false
		}
	}

	return true
}

// HasAny 判断任一指定元素是存在
func (own *UnsafeDict[K, V]) HasAny(keys ...K) bool {
	for _, key := range keys {
		if _, ok := own.items[key]; ok {
			return true
		}
	}

	return false
}

// Get 查询键值对
func (own *UnsafeDict[K, V]) Get(key K) (V, bool) {
	val, ok := own.items[key]
	return val, ok
}

// GetLength 获取字典长度
func (own *UnsafeDict[K, V]) GetLength() int {
	return len(own.items)
}

// GetKeys 获取字典中所有的键
func (own *UnsafeDict[K, V]) GetKeys() []K {
	keys := make([]K, 0, len(own.items))
	for key := range own.items {
		keys = append(keys, key)
	}

	return keys
}

// GetValues 获取字典中所有的值
func (own *UnsafeDict[K, V]) GetValues() []V {
	values := make([]V, 0, len(own.items))
	for _, val := range own.items {
		values = append(values, val)
	}

	return values
}

// GetMap 获取Map
func (own *UnsafeDict[K, V]) GetMap() map[K]V {
	items := make(map[K]V)
	for key, val := range own.items {
		items[key] = val
	}

	return items
}

// Range 遍历字典
func (own *UnsafeDict[K, V]) Range(fn func(key K, val V)) {
	for key, val := range own.items {
		fn(key, val)
	}
}

// Filter 从字典中过滤出符合要求的键值对
func (own *UnsafeDict[K, V]) Filter(fn func(key K, val V) bool) map[K]V {
	items := make(map[K]V)
	for key, val := range own.items {
		if fn(key, val) {
			items[key] = val
		}
	}

	return items
}

// Transform 遍历并更新每个元素
func (own *UnsafeDict[K, V]) Transform(fn func(key K, val V) V) {
	for key, val := range own.items {
		own.items[key] = fn(key, val)
	}
}

// Clear 清空字典
func (own *UnsafeDict[K, V]) Clear() {
	own.items = make(map[K]V)
}
